package com.wennimei.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wennimei.dao.AADAO;
import com.wennimei.domain.Answer;
import com.wennimei.util.HttpUtil;
import com.wennimei.util.Switcher;

@Service
public class AAService {

    private Logger log = Logger.getLogger(AAService.class);

    @Autowired
    private AADAO aadao;

    @Autowired
    private SolrService solrService;

    @Autowired
    private Switcher switcher;

    private static AtomicLong current = new AtomicLong(0);

    private Executor exec = Executors.newFixedThreadPool(10);

    String url = "http://wapiknow.baidu.com/question/%s";

    void init() {
        if (!switcher.isOpen())
            return;

        Long maxId = this.aadao.max();
        if (null == maxId || maxId == 0)
            maxId = 400000000L;

        current.set(maxId);
        for (int i = 0; i < 10; i++) {
            exec.execute(new Runnable() {

                @Override
                public void run() {
                    while (true) {
                        long id = current.getAndAdd(1);
                        try {
                            String link = String.format(url, id);
                            String html = HttpUtil.get(link);
                            String title = null;
                            List<String> results = new ArrayList<String>();
                            Pattern p1 = Pattern.compile("<title>(.*)</title>");
                            Matcher m1 = p1.matcher(html);
                            while (m1.find()) {
                                title = m1.group(1);
                                break;
                            }

                            Pattern p2 = Pattern
                                    .compile(".*<p class=\"ft (bb|p1)\">(.*)?<br/>.*");
                            Matcher m2 = p2.matcher(html);
                            while (m2.find()) {
                                results.add(m2.group(2).replaceAll("<[^>]+>",
                                        ""));
                            }

                            if (null == title || results.isEmpty()) {
                                continue;
                            }

                            aadao.insertQuestion(id, title);
                            for (String s: results) {
                                aadao.insertAnswer(s, id);
                            }
                            solrService.doQAIndex(id, title);
                            log.info("[" + id + "] end init qa;" + title + ";");
                        } catch (Exception e) {
                            continue;
                        }
                    }

                }
            });
        }
    }

    public String getAnswer(String question) {

        List<Long> list = this.solrService.searchQA(question);
        if (null != list && !list.isEmpty()) {
            List<Answer> answers = new ArrayList<Answer>();
            for (Long l: list) {
                answers.addAll(this.aadao.getAnswer(l));
            }

            Collections.shuffle(answers);
            Answer answer = answers.get(0);
            for (Answer a: answers) {
                if (a.getAnswer().length() <= 50) {
                    answer = a;
                    break;
                }
            }

            if (this.spam(answer.getAnswer())) {
                this.aadao.deleteAnswer(answer.getId());
                return this.getAnswer(question);
            }

            String res = answer.getAnswer().replaceAll("&#\\d+\\;", " ");
            return res;
        }
        return "呵呵";
    }

    public boolean spam(String answer) {
        return answer.matches(".*(\\d{5}|淘宝|店铺|网盘|hi|YY|qq|QQ|百度id|百度ID|送分).*");
    }
}
